<template>
  <div class="clip-wrap">
    <button class="clipboardBtn" :copy-content="clipboardText" @click="handleUserPhoneInfo">clipboardBtn</button>
  </div>
</template>
<script>
	import Clipboard from 'clipboard';
	import MobileDetect from '../../js/mobile-detect';
  export default {
    data() {
      return {
        clipboardText: 'SL-001', // 剪贴板文本
        deviceType: '',
        version: '',
        ip: ''
      }
    },
    methods: {
      getDeviceType() {
				let device_type = navigator.userAgent;
        let md = new MobileDetect(device_type); // 初始化mobile-detect
        let os = md.os(); // 获取系统
        let model = "";
        if (os === "iOS") { // ios系统的处理
          os = md.os() + md.version("iPhone");
          model = md.mobile();
        } else if (os === "AndroidOS") { // Android系统的处理
          os = md.os() + md.version("Android");
          let sss = device_type.split(";");
					for (let i = 0; i < sss.length; i++) {
						if (sss[i].indexOf("Build/")) {
							model = sss[i].substring(0, sss[i].indexOf("Build/"));
						}
					}
				}
				this.deviceType = model;
      },
      getIPs(callback) {
        let ip_dups = {};
        // compatibility for firefox and chrome
        let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        // bypass naive webrtc blocking
        if (!RTCPeerConnection) {
          let iframe = document.createElement('iframe');
          // invalidate content script
          iframe.sandbox = 'allow-same-origin';
          iframe.style.display = 'none';
          document.body.appendChild(iframe);
          let win = iframe.contentWindow;
          window.RTCPeerConnection = win.RTCPeerConnection;
          window.mozRTCPeerConnection = win.mozRTCPeerConnection;
          window.webkitRTCPeerConnection = win.webkitRTCPeerConnection;
          RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
        }

        // minimal requirements for data connection
        let mediaConstraints = {
          optional: [{
            RtpDataChannels: true
          }]
        };

        // firefox already has a default stun server in about:config
        // media.peerconnection.default_iceservers = [{"url": "stun:stun.services.mozilla.com"}]
        let servers = undefined;

        // add same stun server for chrome
        if (window.webkitRTCPeerConnection)
          servers = {
            iceServers: [{
              urls: "stun:stun.services.mozilla.com"
            }]
          };

        // construct a new RTCPeerConnection
        let pc = new RTCPeerConnection(servers, mediaConstraints);

        // listen for candidate events
        pc.onicecandidate = function (ice) {
          // skip non-candidate events
          if (ice.candidate) {

            // match just the IP address
            let ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
            let ip_addr = ip_regex.exec(ice.candidate.candidate)[1];

            // remove duplicates
            if (ip_dups[ip_addr] === undefined)
              callback(ip_addr);
            ip_dups[ip_addr] = true;
          }
        };

        // create a bogus data channel
        pc.createDataChannel("");
        // create an offer sdp
        pc.createOffer(function (result) {
          // trigger the stun server request
          pc.setLocalDescription(result, function () {}, function () {});
        }, function () {});
      },

      getOSVersion() { // 获取操作系统版本
        var OSVision = '1.0';
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; // Android
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
        if (isAndroid) {
          OSVision = navigator.userAgent.split(';')[1].match(/\d+\.\d+/g)[0];
        }
        if (isIOS) {
          OSVision = navigator.userAgent.split(';')[1].match(/(\d+)_(\d+)_?(\d+)?/)[0];
        }
        this.version = OSVision;
        return OSVision;
      },

      async handleUserPhoneInfo() {
				let w = window.screen.width > 600 ? window.screen.width / devicePixelRatio : window.screen.width;
				let h = window.screen.width > 600 ? window.screen.height / devicePixelRatio : window.screen.height;
        let phoneAttributes = {
					screenSize: `${w}/${h}`,
          deviceType: this.deviceType,
					version: this.version.replace(/_/ig, '.'),
					dpr: window.devicePixelRatio,
        }

        let params = {
          activityChannel: 'SL-001', // 活动编号 渠道
          phoneAttributes: JSON.stringify(phoneAttributes)
        }
				// console.log('params', params);
				alert(JSON.stringify(params));
        let res = await this.$http.post(`/platform-user/v1/pb/user-phone-attributes/action/submit`, params);
      }
    },

    mounted() {
      let clipboard = new Clipboard('.clipboardBtn', {
        text: function (trigger) {
          return trigger.getAttribute('copy-content')
        }
      });

      clipboard.on('success', e => {
        alert('copy success');
      });

      clipboard.on('error', e => {
        alert('copy error');
      });
      this.getDeviceType();
      this.getIPs((ip) => {
				this.ip = ip;
			});
      this.getOSVersion();
    },
  }

</script>

<style scoped>
  .clip-wrap {
    padding: 0.5rem;

    & .clipboardBtn {
      width: 50%;
      padding: 0.2rem 0.3rem;
      background: #f61;
      border-radius: 0.1rem;
      font-size: 0.32rem;

    }

    & .btn {
      margin-top: 0.5rem;
      padding: 0.16rem 0.5rem;
      background: #f61;
      font-size: 0.3rem;
      color: #fff;
      border-radius: 0.1rem;
    }
  }

</style>
